package edu.gyc.hiblog.shiro;

import cn.hutool.core.bean.BeanUtil;
import edu.gyc.hiblog.model.HiUser;
import edu.gyc.hiblog.service.HiUserService;
import edu.gyc.hiblog.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    HiUserService userService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token=(JwtToken)authenticationToken;
        String userId=jwtUtils.getClaimByToken((String)token.getPrincipal()).getSubject();
        HiUser user = userService.getById(Integer.parseInt(userId));
        log.info("doGetAuthenticationInfo");
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getStatus() == -1) {
            throw new LockedAccountException("账户已被锁定");
        }
        log.info(token.toString());

        AccountProfile profile=new AccountProfile();
        BeanUtil.copyProperties(user,profile);
        return new SimpleAuthenticationInfo(profile,token.getCredentials(),getName());
    }
}
